import { Byte } from "./Byte";

export class ConfigTableData {
    private _buffer: Byte;
    private _head: any;
    private _contentIndex: number;
    constructor(res) {
        let buff = this.decompress(res);
        this._buffer = new Byte(buff);
        let headLen = this._buffer.getUint32();
        let head = this._buffer.getUTFBytes(headLen);
        this._head = JSON.parse(head);
        this._contentIndex = headLen + 4;
    }

    /**压缩的二进制需要zlib解压 */
    decompress(buffer: ArrayBuffer) {
        let inflater = new Zlib.RawInflate(buffer);
        return inflater.decompress();
    }

    public getTable(tableName: string, branch: string = "") {
        let branchName = tableName;
        if (branch) {
            let nameArr = tableName.split(".");
            if (nameArr.length > 1) {
                let fileType = nameArr.pop();
                branchName = nameArr.join(".") + "_" + branch + "." + fileType;
            } else {
                branchName = nameArr[0] + "_" + branch;
            }
        }
        if (!this._head[tableName] && !this._head[branchName]) return null;
        var [start, len] = this._head[branchName] || this._head[tableName];
        this._buffer.pos = start + this._contentIndex;
        var data = this._buffer.readUTFBytes(len);
        return JSON.parse(data);
    }
}